<template>
  <div class="driver-behavior-container">
    <el-card shadow="hover" title="百度驾驶行为分析工具">
    <!-- 新增：主标题区域（突出工具定位与价值） -->
    <div class="page-header">
      <h1 class="main-title">AI驾驶行为分析</h1>
      <p class="sub-title">基于计算机视觉技术，精准识别驾驶中的危险行为（如未系安全带、使用手机等），助力行车安全管控</p>
    </div>
      <!-- 1. 图片上传区域 -->
      <el-upload
        class="upload-section"
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :before-upload="beforeUpload"
        accept="image/jpg,image/png,image/bmp"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
        <div class="upload-tip" slot="tip">支持JPG/PNG/BMP格式，最大4MB</div>
      </el-upload>

      <!-- 2. 参数配置区域 -->
      <div class="param-section" v-if="previewUrl">
        <h4 class="section-title">分析参数配置</h4>
        <el-form :model="paramForm" inline class="param-form">
          <el-form-item label="方向盘位置" prop="wheelLocation">
            <el-select v-model="paramForm.wheelLocation" placeholder="请选择">
              <el-option label="左舵车（中国大陆）" value="1"></el-option>
              <el-option label="右舵车（香港/海外）" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="识别行为类型" prop="type">
            <el-select 
              v-model="paramForm.type" 
              multiple 
              placeholder="默认识别所有类型"
              style="width: 400px;"
            >
              <el-option label="吸烟" value="smoke"></el-option>
              <el-option label="使用手机" value="cellphone"></el-option>
              <el-option label="未系安全带" value="not_buckling_up"></el-option>
              <el-option label="双手离开方向盘" value="both_hands_leaving_wheel"></el-option>
              <el-option label="视角未朝前方" value="not_facing_front"></el-option>
              <el-option label="未佩戴口罩" value="no_face_mask"></el-option>
              <el-option label="打哈欠" value="yawning"></el-option>
              <el-option label="闭眼" value="eyes_closed"></el-option>
              <el-option label="低头" value="head_lowered"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              icon="el-icon-search" 
              @click="doAnalyze"
              :loading="isLoading"
            >
              开始分析
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 3. 图片预览区域 -->
      <div class="preview-section" v-if="previewUrl">
        <h4 class="section-title">图片预览</h4>
        <img :src="previewUrl" class="preview-img" alt="车载图片预览" />
      </div>

      <!-- 4. 分析结果区域（核心修复：统一使用计算属性处理后的数据） -->
      <div class="result-section" v-if="analysisResult">
        <h4 class="section-title">分析结果（日志ID：{{ analysisResult.log_id }}）</h4>
        
        <!-- 基础信息 -->
        <el-descriptions :column="2" border class="base-info">
          <el-descriptions-item label="检测到总人数">{{ analysisResult.person_num }} 人</el-descriptions-item>
          <el-descriptions-item label="检测到驾驶员数">{{ analysisResult.driver_num || 0 }} 人</el-descriptions-item>
        </el-descriptions>

        <!-- 驾驶员位置信息 -->
        <div v-if="analysisResult.person_info && analysisResult.person_info.length > 0">
          <h5 class="sub-title">驾驶员位置信息（像素）</h5>
          <el-table :data="analysisResult.person_info" border stripe class="location-table">
            <el-table-column label="左坐标" prop="location.left" width="100"></el-table-column>
            <el-table-column label="上坐标" prop="location.top" width="100"></el-table-column>
            <el-table-column label="宽度" prop="location.width" width="100"></el-table-column>
            <el-table-column label="高度" prop="location.height" width="100"></el-table-column>
            <el-table-column label="位置检测概率">
              <template #default="scope">{{ (scope.row.location.score * 100).toFixed(2) }}%</template>
            </el-table-column>
          </el-table>

          <!-- 驾驶行为分析（修复：使用behaviorList的处理后数据） -->
          <h5 class="sub-title">驾驶行为分析（概率≥阈值则判定为存在该行为）</h5>
          <el-table :data="behaviorList" border stripe class="behavior-table">
            <el-table-column label="行为类型" prop="behaviorName" width="180"></el-table-column>
            <el-table-column label="识别概率" width="300">
              <template #default="scope">
                <div class="progress-wrap">
                  <!-- 进度条：使用计算好的百分比（保留1位小数，避免0%的视觉空白） -->
                  <el-progress 
                    :percentage="scope.row.scorePercentNum" 
                    :status="scope.row.isAbnormal ? 'warning' : 'success'"
                    width="220"
                    :text-inside="true"
                    :stroke-width="8"
                  ></el-progress>
                  <!-- 文本：显示2位小数，确保精度 -->
                  <span class="percent-text">{{ scope.row.scorePercentText }}%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="建议阈值" width="120">
              <template #default="scope">{{ scope.row.thresholdPercent }}%</template>
            </el-table-column>
            <el-table-column label="结果判定">
              <template #default="scope">
                <el-tag :type="scope.row.isAbnormal ? 'danger' : 'success'">
                  {{ scope.row.resultText }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-empty v-else description="未检测到驾驶员，请上传清晰的车载图片"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage, ElEmpty, ElProgress, ElTag, ElDescriptions, ElDescriptionsItem } from 'element-plus';
import request from '@/utils/request';

// 状态管理
const previewUrl = ref('');
const base64Image = ref('');
const isLoading = ref(false);
const analysisResult = ref(null);

// 参数表单
const paramForm = ref({
  wheelLocation: '1',
  type: []
});

/**
 * 文件选择变化（转换为Base64）
 */
const handleFileChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const result = e.target.result;
    previewUrl.value = result;
    base64Image.value = result.replace(/data:image\/[^;]+;base64,/, '');
    analysisResult.value = null;
  };
  reader.readAsDataURL(file.raw);
};

/**
 * 上传前校验
 */
const beforeUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp';
  const isLt4M = file.size / 1024 / 1024 < 4;

  if (!isImage) {
    ElMessage.error('请选择JPG/PNG/BMP格式的图片！');
    return false;
  }
  if (!isLt4M) {
    ElMessage.error('图片大小不能超过4MB，请压缩后重新上传！');
    return false;
  }
  return true;
};

/**
 * 发起驾驶行为分析
 */
const doAnalyze = async () => {
  if (!base64Image.value) {
    ElMessage.warning('请先选择图片！');
    return;
  }

  try {
    isLoading.value = true;
    const requestParams = {
      base64Image: base64Image.value,
      wheelLocation: paramForm.value.wheelLocation,
      type: paramForm.value.type.join(',')
    };

    const response = await request({
      url: '/driver/behavior/analyze',
      method: 'post',
      data: requestParams
    });

    if (response.code === 200) {
      analysisResult.value = response.data;
      // 调试：打印数据确认科学计数法是否正确转换
      console.log('吸烟行为原始score：', analysisResult.value.person_info[0].attributes.smoke.score);
      console.log('吸烟行为转换后：', Number(analysisResult.value.person_info[0].attributes.smoke.score));
      ElMessage.success('驾驶行为分析成功！');
    } else {
      ElMessage.error('分析失败：' + response.msg);
    }
  } catch (error) {
    ElMessage.error('请求异常：' + (error.msg || '网络错误'));
  } finally {
    isLoading.value = false;
  }
};

/**
 * 核心计算属性：提前处理所有行为数据（解决科学计数法+统一逻辑）
 */
const behaviorList = computed(() => {
  // 校验数据是否存在
  if (!analysisResult.value || !analysisResult.value.person_info[0]?.attributes) {
    return [];
  }

  // 行为类型映射（与后端attributes的下划线字段完全一致）
  const behaviorMap = {
    'smoke': '吸烟',
    'cellphone': '使用手机',
    'not_buckling_up': '未系安全带',
    'both_hands_leaving_wheel': '双手离开方向盘',
    'not_facing_front': '视角未朝前方',
    'no_face_mask': '未佩戴口罩',
    'yawning': '打哈欠',
    'eyes_closed': '闭眼',
    'head_lowered': '低头'
  };

  const attributes = analysisResult.value.person_info[0].attributes;
  return Object.entries(behaviorMap).map(([key, name]) => {
    // 1. 容错：字段不存在时设默认值，避免undefined
    const behavior = attributes[key] || { score: 0, threshold: 0 };
    
    // 2. 彻底处理科学计数法（如3.1143683E-4 → 0.00031143683）
    const score = Number(behavior.score); // 强制转为普通数字
    const threshold = Number(behavior.threshold);
    
    // 3. 统一计算百分比（保留2位小数，避免模板中重复计算）
    const scorePercentText = (score * 100).toFixed(2); // 文本显示用（如"0.03"）
    const scorePercentNum = Number(scorePercentText); // 进度条用（数字类型，如0.03）
    const thresholdPercent = (threshold * 100).toFixed(2); // 阈值显示用（如"48.00"）
    
    // 4. 统一判定结果
    const isAbnormal = score >= threshold; // 是否存在异常行为
    const resultText = isAbnormal ? '存在该行为' : '正常';

    return {
      behaviorName: name,
      score: score,
      scorePercentText: scorePercentText, // 文本显示的百分比（带2位小数）
      scorePercentNum: scorePercentNum,   // 进度条的百分比（数字类型）
      threshold: threshold,
      thresholdPercent: thresholdPercent, // 阈值的百分比（带2位小数）
      isAbnormal: isAbnormal,             // 是否异常（用于状态判断）
      resultText: resultText              // 结果文本（用于标签显示）
    };
  });
});
</script>

<style scoped>
.driver-behavior-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}
.sub-title {
  font-size: 14px;
  color: #666;
  max-width: 800px;
  margin: 0 auto;
}
.upload-section {
  margin-bottom: 25px;
  .el-upload--picture-card {
    width: 120px;
    height: 120px;
    line-height: 120px;
  }
  .upload-tip {
    text-align: center;
    margin-top: 10px;
    color: #666;
    font-size: 12px;
  }
}

.param-section {
  margin-bottom: 25px;
  padding: 15px;
  background: #f9fafc;
  border-radius: 4px;
  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 15px;
    color: #409eff;
    border-left: 4px solid #409eff;
    padding-left: 10px;
  }
  .param-form {
    margin-top: 10px;
    .el-form-item {
      margin-right: 20px;
      margin-bottom: 15px;
    }
  }
}

.preview-section {
  margin-bottom: 25px;
  text-align: center;
  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 15px;
    color: #409eff;
    text-align: left;
    border-left: 4px solid #409eff;
    padding-left: 10px;
  }
  .preview-img {
    max-width: 600px;
    max-height: 400px;
    border: 1px solid #eee;
    border-radius: 4px;
  }
}

.result-section {
  margin-top: 25px;
  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 20px;
    color: #409eff;
    border-left: 4px solid #409eff;
    padding-left: 10px;
  }
  .base-info {
    margin-bottom: 20px;
    .el-descriptions-item {
      color: #666;
      &__label {
        font-weight: 500;
        color: #333;
      }
    }
  }
  .sub-title {
    font-size: 14px;
    font-weight: 500;
    margin: 20px 0 10px;
    color: #666;
  }
  .location-table, .behavior-table {
    margin-bottom: 20px;
    width: 100%;
    th {
      background-color: #f5f7fa;
      font-weight: 500;
    }
    td {
      color: #666;
      vertical-align: middle;
    }
  }
  .progress-wrap {
    display: flex;
    align-items: center;
    .percent-text {
      margin-left: 15px;
      color: #333;
      font-weight: 500;
    }
  }
}
</style>
